package com.inventory.service.impl;

import com.inventory.model.Product;
import com.inventory.repository.ProductRepository;
import com.inventory.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductRepository productRepository;

    @Override
    public Product saveProduct(Product product) {
        return productRepository.save(product);
    }

    @Override
    public Product updateProduct(Product product) {
        product.setUpdatedAt(LocalDateTime.now());
        return productRepository.save(product);
    }

    @Override
    public void deleteProduct(Long id) {
        Optional<Product> productOpt = productRepository.findById(id);
        if (productOpt.isPresent()) {
            Product product = productOpt.get();
            product.setActive(false);
            product.setUpdatedAt(LocalDateTime.now());
            productRepository.save(product);
        }
    }

    @Override
    public Optional<Product> findById(Long id) {
        return productRepository.findById(id);
    }

    @Override
    public List<Product> findAllProducts() {
        return productRepository.findAll();
    }

    @Override
    public List<Product> findActiveProducts() {
        return productRepository.findByActiveTrue();
    }

    @Override
    public List<Product> findByNameContaining(String name) {
        return productRepository.findByNameContainingAndActiveTrue(name);
    }

    @Override
    public List<Product> findByCategory(String category) {
        return productRepository.findByCategoryAndActiveTrue(category);
    }

    @Override
    public List<Product> findLowStockProducts() {
        return productRepository.findLowStockProducts();
    }

    @Override
    public List<String> getAllCategories() {
        return productRepository.findAllCategories();
    }

    @Override
    public boolean existsByBarcode(String barcode) {
        return productRepository.existsByBarcode(barcode);
    }

    @Override
    @Transactional
    public void updateStock(Long productId, int quantity) {
        Optional<Product> productOpt = productRepository.findById(productId);
        if (productOpt.isPresent()) {
            Product product = productOpt.get();
            
            // 更新库存数量
            int newQuantity = product.getQuantity() + quantity;
            
            // 确保库存不为负数
            if (newQuantity < 0) {
                throw new RuntimeException("库存不足，当前库存: " + product.getQuantity() + ", 请求数量: " + Math.abs(quantity));
            }
            
            product.setQuantity(newQuantity);
            product.setUpdatedAt(LocalDateTime.now());
            productRepository.save(product);
        }
    }
} 